﻿using System.ComponentModel;


namespace Todos.Domain.Entities;

[Description("待办列表")]
public class TodoList : EntityBase, IAggregateRoot, ICreationTime
{
    public required string Name { get; set; }

    public DateTime CreatedTime { get; set; }

    public long UserId { get; set; }

    public virtual User? User { get; set; }

    public virtual List<TodoItem> Items { get; set; } = [];

    public void AddItem(string title, string? description = null)
    {
        var item = new TodoItem()
        {
            Title = title,
            Description = description,
            Status = TodoStatus.Pending,
            IsLocked = false,
            ListId = Id,
            CreatedTime = DateTime.Now
        };
        item.SetId();
        Items.Add(item);
    }

    public void ChangeItemStatus(long itemId, TodoStatus status)
    {
        var item = Items.FirstOrDefault(m => m.Id == itemId);
        if (item == null)
        {
            throw new InvalidOperationException("Item not found");
        }
        item.Status = status;
    }

    public void UpdateItem(long itemId, string title, string? description = null, TodoStatus? status = null, bool? isLocked = null)
    {
        var item = Items.FirstOrDefault(m => m.Id == itemId);
        if (item == null)
        {
            throw new InvalidOperationException("Item not found");
        }
        item.Title = title;
        item.Description = description;
        if (status.HasValue)
        {
            item.Status = status.Value;
        }

        if (isLocked.HasValue)
        {
            item.IsLocked = isLocked.Value;
        }
    }

    public void RemoveItem(long itemId)
    {
        var item = Items.FirstOrDefault(m => m.Id == itemId);
        if (item != null)
        {
            Items.Remove(item);
        }
    }
}

